<?php
/**
 * Created by PhpStorm.
 * User: wodrow
 * Date: 18-1-19
 * Time: 上午11:11
 */

namespace common\components\tools;



class FileHelper extends \yii\helpers\FileHelper
{
    /**
     * @param string $url 只能是类似这种的http://chedai.baozeqiche.com/Uploads/2018/11/154113098091120441.jpg
     * @return bool|string
     */
    public static function downloadTmpFileFromUrl($url)
    {
        $tmp_file = basename($url);
        $tmp_path = \Yii::getAlias("@tmp_root/{$tmp_file}");
        file_put_contents($tmp_path, file_get_contents($url));
        return $tmp_path;
    }

    public static function downloadTmpFileFromBase64($base64)
    {
        preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64, $result);
        $type = $result[2];
        $new_file = date('Ymd',time())."_".rand(1000, 9999).".{$type}";
        $tmp_path = \Yii::getAlias("@tmp_root/{$new_file}");
        file_put_contents($tmp_path, $base64);
        return $tmp_path;
    }

    /** 文件转base64输出
     * @param  String $file 文件路径
     * @return String base64 string
     */
    public static  function fileToBase64($file){
        $base64_file = '';
        if(file_exists($file)){
            $mime_type= mime_content_type($file);
            $base64_data = base64_encode(file_get_contents($file));
            $base64_file = 'data:'.$mime_type.';base64,'.$base64_data;
        }
        return $base64_file;
    }

    /**
     * base64去header
     * @param string $base64
     * @return string
     */
    public static function removeDataHeaderForBase64($base64)
    {
        $base64 = str_replace('data:image/jpeg;base64,', '', $base64);
        $base64 = str_replace('data:image/jpg;base64,', '', $base64);
        $base64 = str_replace('data:image/png;base64,', '', $base64);
        $base64 = str_replace('data:image/gif;base64,', '', $base64);
        return $base64;
    }

    /**
     * 获取文件后缀名
     * @param $file
     * @return mixed
     */
    public static function getExtensionName1($file)
    {
        return pathinfo($file, PATHINFO_EXTENSION);
    }

    /**
     * Baca isi sebuah file
     *
     * @param string $filename
     * @return string
     */
    public static function readFile($filename) {
        $fo = fopen($filename, 'r');
        $scr = fread($fo, filesize($filename));
        fclose($fo);
        return $scr;
    }

    public static function renderSourceCode($filename, $lang = 'php') {
        echo Html::beginTag('pre', [
            'class' => 'line-numbers'
        ]);
        echo Html::beginTag('code', [
            'class' => 'language-'.$lang
        ]);
        echo htmlentities(FileHelper::readFile($filename));
        echo Html::endTag('code');
        echo Html::endTag('pre');
    }

    /**
     * Menghapus seluruh file dalam sebuah directory
     *
     * @param string $dir
     */
    public static function deleteFiles($dir) {
        if (is_dir($dir)) {
            array_map('unlink', glob($dir."*"));
        }
    }

    /**
     * Get the class "basename" of the given object / class.
     *
     * @param  string|object  $class
     * @return string
     */
    public static function classBasename($class)
    {
        $class = is_object($class) ? get_class($class) : $class;
        return basename(str_replace('\\', '/', $class));
    }

    /**
     * description: 图像等比例压缩
     * @param string $path 输出路径
     * @param string|null $out_path 输出路径
     * @param int $max_width 最大宽度
     * @param int $max_height 最大高度
     * @return bool
     */
    public static function resizeImage($path, $out_path = null, $max_width = 1600, $max_height = 1600)
    {
        $resize_width_tag = $resize_height_tag = $width_ratio = $height_ratio = $ratio = 0;
        try {
            list($width, $height, $type, $attr) = getimagesize($path);
            $imageinfo = array(
                'width'=>$width,
                'height'=>$height,
                'type'=>image_type_to_extension($type,false),
                'attr'=>$attr
            );
            $fun = "imagecreatefrom".$imageinfo['type'];
            $im = $fun($path);
            $width = imagesx($im);
            $height = imagesy($im);
            if (!is_dir(dirname($out_path))) {
                mkdir(dirname($out_path), 0755, true);
            }
            if (($max_width && $width > $max_width) || ($max_height && $height > $max_height)) {
                if ($max_width && $width > $max_width) {
                    $width_ratio = $max_width / $width;
                    $resize_width_tag = true;
                }
                if ($max_height && $height > $max_height) {
                    $height_ratio = $max_height / $height;
                    $resize_height_tag = true;
                }
                if ($resize_width_tag && $resize_height_tag) {
                    if ($width_ratio < $height_ratio)
                        $ratio = $width_ratio;
                    else
                        $ratio = $height_ratio;
                }
                if ($resize_width_tag && !$resize_height_tag)
                    $ratio = $width_ratio;
                if ($resize_height_tag && !$resize_width_tag)
                    $ratio = $height_ratio;
                $new_width = $width * $ratio;
                $new_height = $height * $ratio;
                if (function_exists("imagecopyresampled")) {
                    $new_im = imagecreatetruecolor($new_width, $new_height);
                    imagecopyresampled($new_im, $im, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
                } else {
                    $new_im = imagecreate($new_width, $new_height);
                    imagecopyresized($new_im, $im, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
                }
                $res = imagejpeg($new_im, !empty($out_path) ? $out_path : $path);
                imagedestroy($new_im);
            } else {
                $res = imagejpeg($im, !empty($out_path) ? $out_path : $path);
            }
            return $res;
        } catch (\Exception $e) {
            var_dump($e->getMessage());
            return false;
        }
    }
}